<template>
  <div>
    <van-nav-bar
      title="添加朋友"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-search v-model="searchText" placeholder="请输入昵称" />
    <div
      class="searchBar"
      v-show="searchText.trim() !== '' && !searchResult"
      @click="goSearch"
    >
      <div>
        <van-icon name="search" />
      </div>
      <div>
        <span>搜索：</span>
        <span>{{ searchText }}</span>
      </div>
    </div>
    <div class="searchResult">
      <div
        v-for="item in searchResult"
        :key="item.uid"
        class="cell"
        @click="goToAdd(item)"
      >
        <van-image :src="item.userAvatar || defaultAvatar" fit="cover" />
        <span>{{ item.userName }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { ref, reactive, watch } from "vue";
import { searchUser, isFriend } from "@/api/user";
import defaultAvatar from "@/assets/cat.jpeg";

const userInfo = JSON.parse(localStorage.getItem("userInfo"));
const router = useRouter();
const searchText = ref("");
const searchResult = ref(null);
watch(searchText, () => {
  searchResult.value = null;
});
const goToAdd = (e) => {
  isFriend({
    friendId: e.uid,
  }).then((res) => {
    if (res.code === 400 && e.userName !== userInfo.userName) {
      // 使用 History API 方式传递和接收
      router.push({
        name: "IdCard",
        state: { userInfo: { ...e } },
      });
    } else {
      showFailToast("该用户已经是您的好友了");
    }
  });
};
const goSearch = () => {
  searchUser({
    keyword: searchText.value,
  }).then((res) => {
    if (res.code === 200) {
      searchResult.value = res.data.userList;
    }
  });
};
const onClickLeft = () => {
  router.go(-1);
};
</script>

<style scoped lang="scss">
.cell {
  display: flex;
  align-items: center;
  margin: 10px 0;
  font-size: 14px;
  border-bottom: 1px solid #eee;
  box-sizing: border-box;
  padding: 10px 15px;

  :deep(.van-image__img, .van-image__error, .van-image__loading) {
    width: 50px;
    height: 50px;
    border-radius: 5px;
    margin-right: 10px;
  }
}

.searchBar {
  display: flex;
  margin: 10px 15px;
  align-items: center;

  & > div:nth-child(2) {
    font-size: 14px;

    & > span:first-child {
      font-weight: bold;
    }

    & > span:nth-child(2) {
      color: #07c15e;
    }
  }

  & > div:first-child {
    width: 40px;
    height: 40px;
    background-color: #07c15e;
    color: #fff;
    font-size: 20px;
    text-align: center;
    line-height: 40px;
    border-radius: 5px;
    margin-right: 5px;
  }
}
</style>
